package com.lechuang.system.controller;

import cn.hutool.core.lang.UUID;
import com.lechuang.common.result.Result;
import com.lechuang.file.service.OssTemplate;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;

@RestController
@Tag(name = "文件相关")
@RequestMapping("/file")
public class FileController {
    @Resource
    private OssTemplate ossTemplate;

    @PostMapping("/upload")
    @Operation(summary = "上传文件")
    public Result<String> upload(@RequestPart @RequestParam(value = "file") MultipartFile file, @RequestParam Boolean hasUuid) {
        String url = this.uploadFile(file, hasUuid);
        return Result.success(url);
    }

    @PostMapping("/batchUpload")
    @Operation(summary = "批量上传文件")
    public Result<String> batchUpload(@RequestPart @RequestParam(value = "file") MultipartFile[] files, @RequestParam Boolean hasUuid) {
        StringJoiner sj = new StringJoiner(",");
        for (MultipartFile file : files) {
            String url = this.uploadFile(file, hasUuid);
            sj.add(url);
        }
        return Result.success(sj.toString());
    }

    private String uploadFile(MultipartFile file, Boolean hasUuid){
        try {
            String fileName;
            if(hasUuid){
                fileName = UUID.fastUUID() + file.getOriginalFilename();
            }else{
                fileName = file.getOriginalFilename();
            }
            InputStream inputStream = file.getInputStream();
            ossTemplate.putObject(fileName, inputStream, file.getContentType());
            return ossTemplate.getObjectURL(fileName);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}
